<template>
  <div class="personal-info">
    <el-card class="info-card">
      <div class="avatar-section">
        <el-avatar :size="80" :src="user.userProfilePictureSrc || defaultAvatar"></el-avatar>
        <div class="username">{{ user.userNickname }}</div>
        <div v-if="isEditing" class="avatar-upload">

            <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            action="http://localhost:9093/file/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-error="handleAvatarError"
            :before-upload="beforeAvatarUpload"
            :auto-upload="true"
          >
            <el-button size="small" type="primary">上传头像</el-button>
          </el-upload>
        </div>
      </div>
      <el-divider></el-divider>
      <el-form
        ref="formRef"
        :model="user"
        label-width="120px"
        class="user-form"
        :disabled="!isEditing"
      >

        <el-form-item label="用户名">
          <el-input v-model="user.userName" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="user.userNickname" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="user.userRealname" />
        </el-form-item>
        <el-form-item label="性别">
           <el-select
                v-model="user.userGender"
                placeholder="请选择性别"
                style="width: 100%"
              >
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
            v-model="user.userBirthday"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择生日"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="user.createTime" disabled />
        </el-form-item>

      </el-form>
      <div class="actions">
        <el-button v-if="!isEditing" type="primary" @click="startEdit">编辑信息</el-button>
        <el-button v-else type="primary" @click="saveInfo">保存</el-button>
        <el-button v-if="isEditing" @click="cancelEdit">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

const user = ref({
  id: '',
  createTime: '',
  userName: '',
  userNickname: '',
  userRealname: '',
  userProfilePictureSrc: '',
  userGender: '',
  userBirthday: ''
})

const formRef = ref()
const uploadRef = ref()
const isEditing = ref(false)
const originalUser = ref({})
const selectedAvatarFile = ref(null)

// 获取用户信息
const fetchUserInfo = async () => {
  try {

    const response = await request.get('/user/getUserInfo')
    if (response.data.code === 200) {
      user.value = response.data.data
    } else {
      ElMessage.error('获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息出错:', error)
    ElMessage.error('获取用户信息异常')
  }
}

// 开始编辑
const startEdit = () => {
  // 保存原始数据
  originalUser.value = { ...user.value }
  user.value.id = localStorage.getItem('userId')
  isEditing.value = true
}

// 保存信息
const saveInfo = async () => {
  try {
    const updatedUser = {
      id: user.value.id,
      userName: user.value.userName,
      userNickname: user.value.userNickname,
      userRealname: user.value.userRealname,
      userGender: user.value.userGender,
      userBirthday: user.value.userBirthday,
      userProfilePictureSrc: user.value.userProfilePictureSrc
     }
    const response = await request.put('/user/updateUserInfo', updatedUser)
    if (response.data.code === 200) {
      ElMessage.success('用户信息更新成功')
      sessionStorage.removeItem('userNickname')
      sessionStorage.setItem('userNickname', user.value.userNickname)
      isEditing.value = false
    } else {
      ElMessage.error('用户信息更新失败: ' + response.data.msg)
    }
  } catch (error) {
    console.error('更新用户信息出错:', error)
    ElMessage.error('用户信息更新异常')
  }
}

// 取消编辑
const cancelEdit = () => {
  // 恢复原始数据
  user.value = { ...originalUser.value }
  isEditing.value = false
  selectedAvatarFile.value = null
}
// 头像上传相关函数
const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    user.value.userProfilePictureSrc = response.data
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error('头像上传失败: ' + (response.msg || response.message))
  }
}

const handleAvatarError = (error) => {
  console.error('头像上传出错:', error)
  ElMessage.error('头像上传失败: ' + (error.response?.data?.message || error.message))
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.personal-info {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.info-card {
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background-color: #fff;
  width: 100%;
}

.avatar-section {
  text-align: center;
  margin-bottom: 20px;
}

.username {
  margin-top: 10px;
  font-size: 18px;
  font-weight: bold;
}

.avatar-upload {
  margin-top: 15px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.user-form {
  margin: 20px 0;
}

.actions {
  text-align: center;
  margin-top: 20px;
}

.actions .el-button {
  margin: 0 10px;
}
</style>
